import { ref, provide, inject, InjectionKey, Ref } from "vue";

export interface FormItemPopoverState {
  currentPopoverItem: Ref<any>;
  showPopover: (e: MouseEvent, item: any) => void;
  hidePopover: () => void;
}

const FormItemPopoverKey = Symbol() as InjectionKey<FormItemPopoverState>;

export function provideFormItemPopover() {
  const popoverVisible = ref(false);
  const virtualElement = ref<any>({ getBoundingClientRect: () => ({}) });
  const currentPopoverItem = ref<any>(null);

  const showPopover = (e: MouseEvent, item: any) => {
    const rect = (e.target as HTMLElement).getBoundingClientRect();
    virtualElement.value = {
      getBoundingClientRect() {
        return {
          width: rect.width,
          height: rect.height,
          x: rect.x,
          y: rect.y,
          top: rect.top,
          left: rect.left,
          right: rect.right,
          bottom: rect.bottom
        };
      }
    };
    currentPopoverItem.value = item;
    popoverVisible.value = true;
  };

  const hidePopover = () => {
    popoverVisible.value = false;
  };

  provide(FormItemPopoverKey, {
    currentPopoverItem,
    showPopover,
    hidePopover
  });

  return {
    popoverVisible,
    virtualElement,
    currentPopoverItem,
    hidePopover
  };
}

export function useFormItemPopover() {
  const context = inject(FormItemPopoverKey);
  if (!context) {
    throw new Error("useFormItemPopover must be used within a provider");
  }
  return context;
}
